package com.example.demo.util;

/**
 * ClassName:DBConnectUtil
 * Package:com.atguigu.xunce.flink.sink
 * TODO:
 *
 * @date:2021/8/9 14:00
 * @author:Vicky(陈烟星)
 */

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnectUtil {

    private static final Logger log = LoggerFactory.getLogger(DBConnectUtil.class);


    /**
     * 获取数据库连接
     *
     * @param url
     * @param user
     * @param password
     * @return
     * @throws SQLException
     */
    public static Connection getConnection(String url, String user, String password) {
        Connection conn = null;
        try {
            if (url.contains("mysql")){
                Class.forName("com.mysql.jdbc.Driver");
            }else if (url.contains("oracle")){
                Class.forName("oracle.jdbc.driver.OracleDriver");
            }

        } catch (ClassNotFoundException e) {
            log.error("获取数据库jdbc.Driver失败");
            e.printStackTrace();
        }
        try {
            conn = DriverManager.getConnection(url, user, password);
            log.info("获取连接:{} 成功...", conn);
        } catch (Exception e) {
            log.error("获取连接失败，url:" + url + ",user:" + user);
        }
        if (conn != null) {
            //设置手动提交
            try {
                conn.setAutoCommit(false);
            } catch (SQLException e) {
                log.error("设置手动提交失败，url:" + url + ",user:" + user);
            }
        }

        return conn;
    }


    /**
     * 事务提交
     *
     * @param conn
     */
    public static void commit(Connection conn) {
        if (conn != null) {
            try {
                conn.commit();
            } catch (SQLException e) {
                log.error("提交事物失败,Connection:" + conn);
                e.printStackTrace();
            }
        }
    }

    /**
     * 事务回滚
     *
     * @param conn
     */
    public static void rollback(Connection conn) {
        if (conn != null) {
            try {
                conn.rollback();
            } catch (SQLException e) {
                log.error("事物回滚失败,Connection:" + conn);
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭连接
     *
     * @param conn
     */
    public static void close(Connection conn) {
        if (conn != null) {
            try {
                log.info("关闭连接,Connection:" + conn);
                conn.close();
            } catch (SQLException e) {
                log.error("关闭连接失败,Connection:" + conn);
                e.printStackTrace();
            }
        }
    }

}
